#include "bin_thread_tree.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN_MAX 512

char buffer[LEN_MAX];

// action 函数
bool printStr(void *str) { return printf("%s", (char *)str) >= 0; }

int main() {
  bitree tree = bit_tree_create((cmp_func_t *)strcmp, NULL);

  // 修改成你自己的路径
  FILE *fp = NULL;

  fopen_s(&fp, "D:/git/c-general-data-structure/tree/bin_thread_tree/text", "r"); 

  if (fp == NULL) {
    fprintf(stderr, "error open file \n");
    exit(EXIT_FAILURE);
  }

  while (fgets(buffer, LEN_MAX, fp) != NULL) { // 读取每一行
    size_t len = strlen(buffer);
    if (!bit_tree_insert(tree, buffer, len + 1)) // 将文本数据复制到树结构中
      break;
  }

  if (!feof(fp)) {
    fprintf(stderr, "sortlines: Error reading or storing text input.\n");
    exit(EXIT_FAILURE);
  }

  fclose(fp);

  int n = bit_tree_in_order(tree, printStr); // LNR输出, 也就是按字符排序
  fprintf(stderr, "\nsortlines: Printed %d lines.\n", n);

  bit_tree_thread(tree);

  printf("\n");

  bit_tree_in_order_thread(tree, printStr);

    printf("\n");

  bit_tree_rev_in_order_thread(tree, printStr);

  bit_tree_destory(tree);
  return 0;
}

// 0: child类型, 1: thread类型 _指针地址
//
//              _0 e 0_
//             ╱       ╲
//         _1 a 0_   _1 f 0_
//                ╲         ╲
//              _0 d 1_   _1 g 0_
//             ╱                 ╲
//         _0 c 1_             _1 h 0_
//        ╱
//    _0 b 1_